package com.yxjx.duoxue.comment;

import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.Executors;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.yxjx.duoxue.BaseActionBarActivity;
import com.yxjx.duoxue.R;
import com.yxjx.duoxue.Yx;
import com.yxjx.duoxue.customview.autolist.AutoListView;
import com.yxjx.duoxue.customview.autolist.AutoListView.OnLoadListener;
import com.yxjx.duoxue.customview.autolist.AutoListView.OnRefreshListener;
import com.yxjx.duoxue.datamodel.DMAllComments;
import com.yxjx.duoxue.datamodel.DMComment;
import com.yxjx.duoxue.datamodel.DMCommentLevelAvg;
import com.yxjx.duoxue.datamodel.course.DMCourse;
import com.yxjx.duoxue.datamodel.school.DMSchool;
import com.yxjx.duoxue.my.UserLoginActivity;
import com.yxjx.duoxue.network.NwUtils;
import com.yxjx.duoxue.network.UserLoginResponse;
import com.yxjx.duoxue.utils.UIHelper;
import com.yxjx.duoxue.utils.Utils;

public class DetailedCommentActivity extends BaseActionBarActivity implements
		OnRefreshListener, OnLoadListener {

	public static final int MSG_LOAD_ALL = 1;
	public static final int MSG_LOAD_MORE = 2;

	public static final int REQ_CODE_LOGIN_FOR_ADD_COMMENT = 1;
	public static final int REQ_CODE_ADD_COMMENT_DONE = 2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_detail_comment);
		customizeActionBarTitle("点评详情");

		mCommentType = getIntent().getExtras().getInt(
				CommentFunctionView.KEY_COMMENT_TYPE);
		mItemId = getIntent().getExtras().getString(
				CommentFunctionView.KEY_ITEM_ID);

		mList = (AutoListView) findViewById(R.id.list);
		mAdapter = new MyListAdapter();
		mList.setAdapter(mAdapter);
		mList.setOnRefreshListener(this);
		mList.setOnLoadListener(this);
		showLoading(true);
		doLoadComments();
	}

	private void showLoading(boolean show) {
		findViewById(R.id.loading).setVisibility(
				show ? View.VISIBLE : View.GONE);
		findViewById(R.id.root).setVisibility(
				show ? View.INVISIBLE : View.VISIBLE);
	}

	class MyListAdapter extends BaseAdapter {
		public static final int TYPE_HEAD = 0;
		public static final int TYPE_RECORD = 1;
		public static final int TYPE_COUNT_TOTAL = 2;

		@Override
		public int getCount() {
			return mAllComments == null ? 0 : (mAllComments.size() + 1);
		}

		@Override
		public int getItemViewType(int position) {
			if (position == 0) {
				return TYPE_HEAD;
			} else {
				return TYPE_RECORD;
			}
		}

		@Override
		public int getViewTypeCount() {
			return TYPE_COUNT_TOTAL;
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			View ret = null;
			if (getItemViewType(arg0) == TYPE_HEAD) {
				if (arg1 == null) {
					ret = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_comment_head, null);
				} else {
					ret = arg1;
				}
				UIHelper.setClickListener(ret, R.id.add_comment, new View.OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						if (UserLoginResponse.getInstance(getApplicationContext()) == null) {
							startActivityForResult(new Intent(getApplicationContext(),
									UserLoginActivity.class), REQ_CODE_LOGIN_FOR_ADD_COMMENT);
						} else {
							addComment();
						}
					}
				});
				
				((TextView) ret.findViewById(R.id.name)).setText(mTitle);
				((RatingBar) ret.findViewById(R.id.rating)).setRating(Utils.floatFrom(mTotalComment.getAvgTotalLevel()));
				((TextView) ret.findViewById(R.id.detailed_scores).findViewById(R.id.rating_teach)).setText(mTotalComment.getAvgLevel1());
				((TextView) ret.findViewById(R.id.detailed_scores).findViewById(R.id.rating_teacher)).setText(mTotalComment.getAvgLevel2());
				((TextView) ret.findViewById(R.id.detailed_scores).findViewById(R.id.rating_environ)).setText(mTotalComment.getAvgLevel3());
				((TextView) ret.findViewById(R.id.detailed_scores).findViewById(R.id.rating_travel)).setText(mTotalComment.getAvgLevel4());
				
			} else if (getItemViewType(arg0) == TYPE_RECORD) {
				if (arg1 == null) {
					ret = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_comment_record_wrapper, null);
				} else {
					ret = arg1;
				}
				DMComment comment = mAllComments.get(arg0 - 1);
				CommentItemView itemView = (CommentItemView) ret.findViewById(R.id.commentItemView);
				ret.findViewById(R.id.commentItemView_divider).setVisibility(View.GONE);
				itemView.setComment(comment);
			}
			return ret;
		}
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			ArrayList<DMComment> comments = (ArrayList<DMComment>) msg.obj;
			switch (msg.what) {
			case MSG_LOAD_ALL:
				mAllComments = comments;
				mAdapter.notifyDataSetChanged();
				showLoading(false);
				resetScroll();
				mList.onRefreshComplete();
				break;
			case MSG_LOAD_MORE:
				mAllComments.addAll(comments);
				mAdapter.notifyDataSetChanged();
				mList.onLoadComplete();
				break;
			default:
				break;
			}
			mList.setResultSize(comments == null ? 0 : comments.size());
		}
	};

	private AutoListView mList;
	private MyListAdapter mAdapter;
	private ArrayList<DMComment> mAllComments = new ArrayList<DMComment>();
	private int mCommentType;
	private String mItemId;

	// for show in UI
	private String mHeadIcon = "";
	private String mTitle = "";
	private DMCommentLevelAvg mTotalComment = new DMCommentLevelAvg();

	private void doLoadComments() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				ArrayList<DMComment> comments = loadComments();
				// 加载第一项相关的信息
				loadItemInfo();
				Message msg = mHandler.obtainMessage(MSG_LOAD_ALL, comments);
				mHandler.sendMessage(msg);
			}
		}).start();
	}

	private void doLoadMoreComments() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				ArrayList<DMComment> moreComments = loadMoreComments();
				Message msg = mHandler.obtainMessage(MSG_LOAD_MORE,
						moreComments);
				mHandler.sendMessage(msg);
			}
		}).start();
	}

	private ArrayList<DMComment> loadComments() {
		JSONObject params = new JSONObject();
		try {
			params.put("type", "" + convertType(mCommentType));
			params.put("id", mItemId);
			params.put("startIndex", "1");
			params.put("count", 20);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return loadCommentsByParams(params, DetailedCommentActivity.this);
	}

	private void loadItemInfo() {
		if (mCommentType == Yx.TYPE_ITEM_COURSE) {
			DMCourse course = loadCourse(mItemId);
			if (course != null) {
				mTitle = course.getCourseName();
				mTotalComment = course.getCourseCommentLevel();
				mHeadIcon = course.getHeadImageUrl();
			}
		} else if (mCommentType == Yx.TYPE_ITEM_SCHOOL) {
			DMSchool school = loadSchool(mItemId);
			if (school != null) {
				mTitle = school.getFullSchoolName();
				mTotalComment = school.getSchoolCommentLevel();
				mHeadIcon = school.getSchoolImage();
			}
		}
	}

	private DMCourse loadCourse(String courseId) {
		JSONObject params = new JSONObject();
		try {
			params.put(NwUtils.KEY_AREA, "0_0");
			params.put(NwUtils.KEY_ID, courseId);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		try {
			DMCourse course = (DMCourse) NwUtils.requestDataInfo(
					NwUtils.REQ_COURSE_INFO, params,
					DetailedCommentActivity.this);
			return course;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	private DMSchool loadSchool(String schoolId) {
		JSONObject params = new JSONObject();
		try {
			params.put(NwUtils.KEY_ID, schoolId);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		try {
			DMSchool school = (DMSchool) NwUtils.requestDataInfo(
					NwUtils.REQ_SCHOOL_INFO, params,
					DetailedCommentActivity.this);
			return school;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	private ArrayList<DMComment> loadMoreComments() {
		JSONObject params = new JSONObject();
		try {
			params.put("type", "" + convertType(mCommentType));
			params.put("id", mItemId);
			// mAdapter 长度比 mAllComments 大一
			params.put("startIndex", mAllComments.size() + 1);
			params.put("count", 20);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return loadCommentsByParams(params, DetailedCommentActivity.this);
	}

	// 0默认查询所有评论,1课程评论,2活动评论,3学校评论,4老师评论。
	public static String convertType(int type) {
		if (type == Yx.TYPE_ITEM_SCHOOL) {
			return "3";
		} else if (type == Yx.TYPE_ITEM_COURSE) {
			return "1";
		} else {
			return "0";
		}
	}

	/**
	 * For usage in CourseIntroduction and SchoolIntroduction.
	 * 
	 * @param params
	 * @return
	 */
	public static ArrayList<DMComment> loadCommentsByParams(JSONObject params,
			Context context) {
		try {
			ArrayList<?> commentsTemp = (ArrayList<?>) NwUtils
					.requestDataInfoList(NwUtils.REQ_LIST_COMMENTS, params,
							context);
			ArrayList<DMComment> comments = (ArrayList<DMComment>) commentsTemp;
			return comments;

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * For being used in CourseIntroduction and SchoolIntroduction.
	 * 
	 * @param params
	 * @return
	 */
	public static DMAllComments loadAllCommentsListByParams(JSONObject params,
			Context context) {
		try {
			DMAllComments allComments = NwUtils.requestAllCommentsList(
					NwUtils.REQ_LIST_COMMENTS, params, context);
			return allComments;

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void onLoad() {
		doLoadMoreComments();
	}

	@Override
	public void onRefresh() {
		doLoadComments();
	}

	private void resetScroll() {
		mList.post(new Runnable() {

			@Override
			public void run() {
				mList.setSelection(0);
			}
		});
	}

	/**
	 * Add a comment
	 */
	private void addComment() {
		Intent intent = new Intent(this, AddingCommentsActivity.class);
		intent.putExtra(CommentFunctionView.KEY_COMMENT_TYPE, mCommentType);
		intent.putExtra(CommentFunctionView.KEY_ITEM_ID, mItemId);
		startActivityForResult(intent, REQ_CODE_ADD_COMMENT_DONE);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQ_CODE_ADD_COMMENT_DONE:
			onRefresh();
			break;
		case REQ_CODE_LOGIN_FOR_ADD_COMMENT:
			if (resultCode == RESULT_OK) {
				addComment();
			}
			break;
		default:
			break;
		}
	}

}
